"""

    Use this script to generate an executable for CGL

    Usage: makeexe.py [--pyinstaller=pyinstallerpath]

    If pyinstallerpath is specified, script will use pyinstaller. Otherwise
    it will attempt to use cx_freeze.

    TODO:
        optionally create zips?
            source zip
            exe zip

"""

import subprocess, os, sys, shutil, getopt, re


SCRIPTPATH = os.path.dirname( sys.argv[0] )
DISTFOLDER = os.path.join( SCRIPTPATH, 'distcgl')
BUILDFOLDER = os.path.join( SCRIPTPATH, 'buildcgl')


# header
print ' '*50
print "CGL EXE Generator"
print "-"*50
# parse command line
optlist, args = getopt.getopt(sys.argv[1:], [], ['pyinstaller='])

# default to cx_freeze
exebuilder = 'cx_freeze'

for opt, value in optlist:
    if opt == '--pyinstaller':
        # if pyinstaller path seems correct :P
        if os.path.isfile( value + os.path.sep + 'Makespec.py'):
            exebuilder = 'pyinstaller'
            pyinstallerpath = value
            break
        else:
            print "PyInstaller directory seems invalid. Falling back to cx_Freeze"


print "DELETING OLD BUILD AND DIST FOLDERS"
if os.path.exists( DISTFOLDER):
    shutil.rmtree(DISTFOLDER)
if os.path.exists(BUILDFOLDER):
    shutil.rmtree(BUILDFOLDER)

if exebuilder == 'pyinstaller':
    print "RUNNING PYINSTALLER"

    # if not on windows, make sure it has proper line endings bc pyinstaller cant handle it
    if not sys.platform.startswith('win'):
        # from http://www.java2s.com/Code/Python/Utility/ChangeLFlineendingstoCRLFUnixtoWindows.htm
        data = open('cgl.py', 'rb').read()
        newdata = re.sub("\r?\n", "\n", data)
        f = open('cgl.py', 'wb')
        f.write(newdata)
        f.close()

    print "CREATING SPEC FILE"
    proc = subprocess.Popen( "%s -F -X -n cgl --icon=cgl-logo.ico cgl.py"% os.path.join(pyinstallerpath, "Makespec.py"), shell=True)
    proc.communicate()

    print "BUILDING EXECUTABLE"
    proc = subprocess.Popen( "%s %s"% ( os.path.join(pyinstallerpath, "Build.py"),  'cgl.spec' ), shell=True)
    proc.communicate()

    # create dist folder
    os.mkdir( DISTFOLDER)

    # copy exe there
    if os.path.isfile('cgl.exe'):
        shutil.move('cgl.exe', DISTFOLDER + os.path.sep + 'cgl.exe')
    elif os.path.isfile('cgl'):
        shutil.move('cgl', DISTFOLDER + os.path.sep + 'cgl')
    else:
        print "Executable not found... Locate and move it manually :D"

    # delete spec if found
    if os.path.isfile( 'cgl.spec'):
        os.remove( 'cgl.spec')

elif exebuilder == 'cx_freeze':
    print "RUNNING CX_FREEZE"

    try:
        from cx_Freeze import main
        sys.argv = [sys.argv[0], '--target-dir', '%s'%DISTFOLDER, 'cgl.py']
        main()
    except Exception, e:
        print e
        sys.exit(1)


##    proc = subprocess.Popen( "%s clg.py --target-dir %s"% (os.path.join(freezepath, "freeze"), DISTFOLDER), shell=True)
##    proc.communicate()


if not os.path.isdir(DISTFOLDER):
    print "BUILD FAILED"
    sys.exit(1)

else:
    print "MOVING FILES"
    files = ['readme.txt', 'license.txt', 'example-gameinfo.xml', 'example-gameinfo-condensed.xml', 'cgl-logo.ico']
    for f in files:
        shutil.copy( f, DISTFOLDER + os.path.sep + f)

    # get OS guess
    prefixes = {'win':'win',
                'linux':'linux',
                'darwin':'mac',
                'mac':'mac'}
    plat = sys.platform
    osname = 'other'
    for prefix in prefixes.keys():
        if plat.startswith(prefix):
            osname = prefixes[prefix]

    # get CGL version number
    try:
        import cgl
        version = cgl.VERSION
    except:
        version = ''

    # rename to something useful
    foldername = "cgl-exe-%s_%s" % (osname, version)
    foldername = foldername.lower()

    # check if already exists
    movefolder = True
    if os.path.exists( foldername ):
        # prompt overwrite
        result = raw_input("%s already exists. Overwrite? Y/N:  "%foldername)
        if result.startswith( ('y', 'Y')):
            shutil.rmtree( foldername )
        else:
            print "NOT OVERWRITING - EXE IN %s" % DISTFOLDER
            movefolder = False

    # rename
    if movefolder:
        shutil.move( DISTFOLDER, foldername)
        print "EXE IN %s" % foldername

    # clean up build folder
    print "CLEANING UP"
    if os.path.exists(BUILDFOLDER):
        shutil.rmtree(BUILDFOLDER)

    print "BUILD FINISHED"
    sys.exit(0)